<template>
	<ul class="alphabet">
		<li 
			class="alphabet-item" 
			v-for="item of letters" 
			:key="item"
			:ref="item"
			@click="letterClickHandle"
			@touchstart="touchStartHandle"
			@touchmove="touchMoveHandle"
			@touchend="touchEndHandle"
		>
			{{item}}
		</li>
	</ul>
</template>

<script>
	export default {
		name:'alphabet',
		props: {
			cities:Object
		},
		data() {
			return {
				touchStatus:false,
				timer:null,
				startY:0/*A距离顶部的距离*/
			}
		},
		/*页面渲染完毕，或者更新完毕时*/
		updated() {
			this.startY=this.$refs['A'][0].offsetTop;
		},
		computed: {
			letters() {
				/*定义数组存放所有字母*/
				const letters=[];
				for(let i in this.cities) {
					letters.push(i)
				}
				return letters;
			}
		},
		methods: {
			/**
			 * 点击字母列表
			 * 获取所点击的字母，传递给父组件，再由父组件传递给另外的兄弟组件
			 */
			letterClickHandle(e) {
				this.$emit('change',e.target.innerText)
			},

			/*滑动字母列表事件*/
			touchStartHandle() {
				this.touchStatus=true;
			},
			touchMoveHandle(e) {
				if(this.touchStatus) {
					/**
					 * 函数节流
					 * 优化性能
					 */
					if(this.timer) {
						clearTimeout(this.timer);
					}
					this.timer=setTimeout(() => {
						/*手指所在位置*/
						const touchY=e.touches[0].clientY-81;
						/*手指所在的字母索引*/
						const index=Math.floor((touchY-this.startY)/20);
						if(index>=0 && index<this.letters.length) {
							this.$emit('change',this.letters[index])
						}
					},16)
				}
			},
			touchEndHandle() {
				this.touchStatus=false;
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'styles/varible';
	.alphabet {
		position: absolute;
		top: 1.62rem;
		right: 0;
		bottom: 0;
		width: .4rem;
		display: flex;
		justify-content:center;
		flex-direction:column;
		.alphabet-item {
			line-height: .35rem;
			text-align: center;
			color:$bgColor;
		}
	}
</style>